package com.toman.ui.work.workplan;

import android.app.Dialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.lzy.okhttputils.OkHttpUtils;
import com.lzy.okhttputils.callback.StringCallback;
import com.toman.Enum.BaseEnum;
import com.toman.Enum.NetworkEnum;
import com.toman.Interfaces.NewBaseUrl;
import com.toman.JavaBean.DeviceHouseDayPlanEntity;
import com.toman.JavaBean.DeviceHouseDayPlanMappingEntity;
import com.toman.JavaBean.DeviceHouseMonthDayPlanEntity;
import com.toman.JavaBean.DeviceHouseMonthPlanEntity;
import com.toman.R;
import com.toman.Util.BaseNetUtil;
import com.toman.Util.DefaultAcitonCallback;
import com.toman.Util.DialogUtils;
import com.toman.Util.JsonExcludeNull;
import com.toman.Util.JsonUtils;
import com.toman.Util.SPUtils;
import com.toman.Util.StringUtils;
import com.toman.Util.ToastUtil;
import com.toman.Util.ViewUtil;
import com.toman.bean.ItemListBean;
import com.toman.toolbar.ToolBarActivity;
import com.toman.widget.callback.StringLoadingCallback;
import com.zhy.adapter.recyclerview.CommonAdapter;
import com.zhy.adapter.recyclerview.base.ViewHolder;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Request;
import okhttp3.Response;

public class WorkshopDayPlanAddActivity extends ToolBarActivity {
    CommonAdapter<DeviceHouseDayPlanMappingEntity> adapter;
    List<DeviceHouseDayPlanMappingEntity> list = new ArrayList<>();
    List<DeviceHouseDayPlanMappingEntity> listAll = new ArrayList<>();
    List<DeviceHouseDayPlanMappingEntity> listRemove = new ArrayList<>();

    List<DeviceHouseMonthDayPlanEntity> workdays = new ArrayList<>();
    DeviceHouseDayPlanEntity bean = new DeviceHouseDayPlanEntity();
    DeviceHouseMonthDayPlanEntity MonthItemBean = new DeviceHouseMonthDayPlanEntity();
    DeviceHouseMonthPlanEntity MonthBean = new DeviceHouseMonthPlanEntity();

    List<ItemListBean> beltline = new ArrayList<>();
    @BindView(R.id.tv_dep)
    TextView tvDep;
    @BindView(R.id.rl_product_dep)
    RelativeLayout rlProductDep;
    @BindView(R.id.tv_workday)
    TextView tvWorkday;
    @BindView(R.id.rl_product_workday)
    RelativeLayout rlProductWorkday;
    @BindView(R.id.et_month_plan)
    EditText etMonthPlan;
    @BindView(R.id.et_day_plan)
    EditText etDayPlan;
    @BindView(R.id.tv_title)
    LinearLayout tvTitle;
    @BindView(R.id.lv)
    RecyclerView lv;
    AlertDialog.Builder builder = null;
    @BindView(R.id.tv_ok)
    TextView tvOk;
    @BindView(R.id.tv_default_day)
    TextView tvDefaultDay;
    @BindView(R.id.rl_default_day)
    RelativeLayout rlDefaultDay;
    /*所选日期是否已有计划*/
    boolean isWarkday = false;
    @BindView(R.id.btn_add)
    Button btnAdd;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_workshop_day_plan_add);
        ButterKnife.bind(this);

        initView();
        initIntent();

    }

    private void initIntent() {
        if (getIntent().getSerializableExtra("bean")!=null){
            MonthItemBean = (DeviceHouseMonthDayPlanEntity) getIntent().getSerializableExtra("bean");
            MonthBean = (DeviceHouseMonthPlanEntity) getIntent().getSerializableExtra("beanParent");
            tvWorkday.setText(MonthItemBean.getDay());
            DeviceHouseMonthDayPlanEntity entity=new DeviceHouseMonthDayPlanEntity();
            entity.setDay(MonthItemBean.getDay());
            workdays.add(entity);
            etMonthPlan.setText(MonthItemBean.getPlanOutput()+"");
tvDep.setText(MonthBean.getDepartmentName());
bean.setDepartmentId(MonthBean.getDepartmentId());
            initBeltline();
        }
        if (getIntent().getStringExtra("id")!=null){
            departmentId=getIntent().getStringExtra("id");

            bean.setDepartmentId(Long.valueOf(departmentId));
            tvDep.setText(getIntent().getStringExtra("name"));
            initBeltline();
        }
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.toolbar_finish, menu);

        toolbar.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(MenuItem item) {
                switch (item.getItemId()) {
                    case R.id.menu_finish:
                        add();
                        break;
                }
                return false;
            }
        });

        return true;
    }

    private void initView() {
        baseEnum = BaseEnum.WORKSHOPDAYPLAN;
        initToolBar(baseEnum.add());
        initAdapter();
        lv.setAdapter(adapter);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false) {
        };
        lv.setLayoutManager(linearLayoutManager);
    }

    private void initAdapter() {
        adapter = new CommonAdapter<DeviceHouseDayPlanMappingEntity>(this, R.layout.item_workshop_day_plan_add, list) {
            @Override
            protected void convert(ViewHolder holder, DeviceHouseDayPlanMappingEntity item, final int position) {
                try {
                    holder.setText(R.id.tv_beltline, item.getBeltlineName());
                } catch (Exception e) {
                    e.printStackTrace();
                }

                EditText et_plan = holder.getView(R.id.et_plan);
                if (et_plan.getTag() instanceof TextWatcher) {
                    et_plan.removeTextChangedListener(((TextWatcher) et_plan.getTag()));
                }
                et_plan.setText(item.getPlanOutput() + "");
                Button button = holder.getView(R.id.btn_del);
                button.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        DialogUtils.showDialog(WorkshopDayPlanAddActivity.this, "确定要删除该产线吗", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                list.remove(item);
                                adapter.notifyDataSetChanged();

                            }
                        });
                    }
                });

                TextWatcher textWatcher = new TextWatcher() {
                    @Override
                    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

                    }

                    @Override
                    public void onTextChanged(CharSequence s, int start, int before, int count) {

                    }

                    @Override
                    public void afterTextChanged(Editable s) {

                        try {
                            item.setPlanOutput(Integer.valueOf(s.toString()));
//                            list.get(position).setPlanOutput(Integer.parseInt(s.toString()));
                        } catch (Exception e) {
                            item.setPlanOutput(0);
//                            list.get(position).setPlanOutput(0);
                        }

                    }
                };
                et_plan.addTextChangedListener(textWatcher);
                et_plan.setTag(textWatcher);

            }
        };
    }


    @OnClick({R.id.rl_product_dep, R.id.rl_product_workday, R.id.rl_default_day,R.id.tv_ok, R.id.btn_add})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.rl_product_dep:
                DialogUtils.showDialog(this, NetworkEnum.DEP, mCompanyId, new DefaultAcitonCallback() {
                    @Override
                    public void run(ItemListBean bean1, Dialog dialog) {
                        bean.setDepartmentId(Long.valueOf(bean1.getID()));
                        tvDep.setText(bean1.getName());
                        initBeltline();


                        dialog.dismiss();
                    }
                });
                break;
            case R.id.rl_product_workday:


                if (StringUtils.isEmpty(tvDep.getText().toString())) {
                    ToastUtil.makeText(getApplicationContext(), "请先选择部门");
                    return;
                }

                ViewUtil.getdays2(WorkshopDayPlanAddActivity.this, token, bean.getDepartmentId() + "", workdays, tvWorkday, true, new DefaultAcitonCallback() {
                    @Override
                    public void run(boolean b) {
                        super.run();
                        isWarkday = b;
                        StringBuilder days = new StringBuilder();
                        for (DeviceHouseMonthDayPlanEntity entity : workdays) {
                            if (days.length() <= 0) {
                                days.append(entity.getDay().substring(5));
                            } else {
                                days.append(",").append(entity.getDay().substring(5));
                            }
                        }
                        tvWorkday.setText(days.toString());
                        adapter.notifyDataSetChanged();
                    }
                });
                break;
            case R.id.rl_default_day:
                if (StringUtils.isEmpty(tvDep.getText().toString())) {
                    ToastUtil.makeText(getApplicationContext(), "请先选择部门");
                    return;
                }
                ViewUtil.getDate(this, tvDefaultDay,new DefaultAcitonCallback(){
                    @Override
                    public void run() {
                        super.run();
customer(1,1,tvDefaultDay.getText().toString());
                    }
                });
                break;

            case R.id.tv_ok:
                DialogUtils.showDialog(this, "确认要将所有数据设置为默认值吗", (dialog, which) -> {
                    for (DeviceHouseDayPlanMappingEntity entity : list) {
                        try {
                            entity.setPlanOutput(Integer.valueOf(etDayPlan.getText().toString()));
                        } catch (Exception e) {
                            entity.setPlanOutput(0);
                        }
                    }
                    adapter.notifyDataSetChanged();
                });
                break;
            case R.id.btn_add:
                listRemove.clear();
                listRemove.addAll(listAll);
                listRemove.removeAll(list);
                if (listRemove.size()<=0){
                    ToastUtil.makeText(getApplicationContext(),"没有可添加的产线");
                    return;
                }
                else {
DialogUtils.showAddBeltDialog(this,adapter,list,listRemove);
                }
                break;
        }
    }

    private void initBeltline() {
        Map<String, String> map = new HashMap<>();
        map.put("departmentId", bean.getDepartmentId() + "");
        beltline.clear();
        BaseNetUtil.base(this, NetworkEnum.BELTLINE, beltline, mCompanyId, map, new DefaultAcitonCallback() {
            @Override
            public void run() {
                super.run();
                list.clear();

                for (ItemListBean bean : beltline) {
                    DeviceHouseDayPlanMappingEntity entity = new DeviceHouseDayPlanMappingEntity();
                    entity.setBeltlineId(Long.valueOf(bean.getID()));
                    entity.setBeltlineName(bean.getName());
                    entity.setPlanOutput(0);
                    list.add(entity);
                }
                listAll.clear();
                listAll.addAll(list);


                adapter.notifyDataSetChanged();

            }
        });

    }

    public void add() {
        String[] item = new String[]{"部门", "工作日", "日计划数"};//直接初始化
        if (ViewUtil.isNull(getApplicationContext(), item, tvDep, tvWorkday, etMonthPlan)) {
            return;
        }
        if (list.isEmpty()) {
            ToastUtil.makeText(getApplicationContext(), "产线不得为空");
        }

        StringBuilder days = new StringBuilder();
        for (DeviceHouseMonthDayPlanEntity entity : workdays) {
            if (days.length() <= 0) {
                days.append(entity.getDay());
            } else {
                days.append(",").append(entity.getDay());
            }
        }
//        if (isWarkday) {
//            DialogUtils.showDialog(this, "选择的日期中含非月计划工作日，确定要继续添加车间日计划，并添加或修改车间月计划吗", new DialogInterface.OnClickListener() {
//                @Override
//                public void onClick(DialogInterface dialog, int which) {
//                    send(days);
//                }
//            });
//        } else {
//            send(days);
//        }

check(days);

    }

    private void check(StringBuilder days) {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("departmentId", bean.getDepartmentId() + "");
        map.put("day", days.toString());
        map.put("mappings", list);
        map.put("planOutput", etMonthPlan.getText().toString());
        map.put("defaultDayPlanOutput", etDayPlan.getText().toString());
        String str = JsonUtils.obj2JsonString(map);
        OkHttpUtils
                .post(NewBaseUrl.devicehousemonthplan_validateDuplicateDayPlan)
                .headers("token", token)
                .headers("Content-Type", "application/json")
                .postJson(str)
                .execute(new StringCallback() {
                    @Override
                    public void onResponse(boolean isFromCache, String result, Request request, @Nullable Response response) {
                        Log.i("test", "新增计划: " + result);
                        JSONObject jsonObj = JSON.parseObject(result);
                        int code = jsonObj.getInteger("code");
                        ViewUtil.lagout(code, getApplicationContext());

                        if (code == 0) {
                          send(days);

                        } else if (code==1){
check(jsonObj.getString("msg"),days);
                        }
                        else {
                            ToastUtil.makeText(getApplicationContext(), jsonObj.getString("msg"));

                        }

                    }
                });
    }


    public void check(String title,StringBuilder days){
        DialogUtils.showDialog(this, title, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                send(days);
            }
        });

    }


    private void send(StringBuilder days) {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("departmentId", bean.getDepartmentId() + "");
        map.put("day", days.toString());
        map.put("mappings", list);
        map.put("planOutput", etMonthPlan.getText().toString());
        map.put("defaultDayPlanOutput", etDayPlan.getText().toString());
        String str = JsonUtils.obj2JsonString(map);
        OkHttpUtils
                .post(NewBaseUrl.devicehousedayplan_save)
                .headers("token", token)
                .headers("Content-Type", "application/json")
                .postJson(str)
                .execute(new StringCallback() {
                    @Override
                    public void onResponse(boolean isFromCache, String result, Request request, @Nullable Response response) {
                        Log.i("test", "新增计划: " + result);
                        JSONObject jsonObj = JSON.parseObject(result);
                        int code = jsonObj.getInteger("code");
                        ViewUtil.lagout(code, getApplicationContext());

                        if (code == 0) {
                            SPUtils.put(getApplicationContext(), baseEnum.update(), true);
                           if (getIntent().getSerializableExtra("bean")!=null) {
                               SPUtils.put(getApplicationContext(), BaseEnum.WORKSHOPMONTHPLAN.update(), true);
                           }
                            ToastUtil.makeText(getApplicationContext(), jsonObj.getString("msg"));
                            finish();

                        } else {
                            ToastUtil.error(getApplicationContext(), jsonObj.getString("msg"));
                        }

                    }
                });
    }

    public void customer(Integer page, final Integer type, String search) {
        if (dialog != null) {
            dialog.dismiss();
        }


        OkHttpUtils
                .get(NewBaseUrl.devicehousedayplan_appselectlist)
                .params("token", token)
                .params("day", search)
                .params("departmentId", departmentId)

                .execute(new StringLoadingCallback(this) {
                    @Override
                    public void onResponse(boolean isFromCache, String result, Request request, @Nullable Response response) {
                        Log.i("test", baseEnum.name + ": " + result);
                        if (type == 1) {
                            list.clear();
                        }
                        JSONObject jsonObj = JSON.parseObject(result);
                        int code = jsonObj.getInteger("code");
                        ViewUtil.lagout(code, getApplicationContext());
                        if (code == 0) {

                            List<DeviceHouseDayPlanMappingEntity> jsonArray = new ArrayList<>(JsonExcludeNull.parseArrayExcludeNull(jsonObj.getString("list"), DeviceHouseDayPlanMappingEntity.class));
//                            部门是一致的就不覆盖了
//                            bean = JSON.parseObject(jsonObj.getString("entity"), DeviceHouseDayPlanEntity.class);
                            ;
                            list.addAll(jsonArray);

                            if (list.size() == 0) {
                                ToastUtil.makeText(getApplicationContext(), "该日未配置");

                            }
                            adapter.notifyDataSetChanged();



                        } else {
                            ToastUtil.error(getApplicationContext(), jsonObj.getString("msg"));
                        }

                    }
                });
    }

}
